package com.iexbuy.ihg.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.baidu.navisdk.util.common.StringUtils;
import com.iexbuy.ihg.App;
import com.iexbuy.ihg.R;
import com.iexbuy.ihg.common.CommUtil;
import com.iexbuy.ihg.entity.UserProfile;
import com.iexbuy.ihg.net.ServiceHelper;
import com.iexbuy.ihg.pay.PayUtil;
import com.iexbuy.ihg.entity.XiaoFeiOrderConfirmObject;
import com.iexbuy.ihg.utils.JsonUtils;
import com.iexbuy.ihg.utils.StringUtil;
import com.iexbuy.ihg.utils.ToastUtils;
import com.iexbuy.ihg.wxapi.WXPayEntryActivity;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.math.BigDecimal;
import java.util.HashMap;

public class PayConfirmFragment extends BaseFragment {
	
	private static PayConfirmFragment homeFragmentInstent;

	@ViewInject(R.id.msgListLayout)
	private PullToRefreshLayout msgListRefreshLayout;
	@ViewInject(R.id.listView)
	private ListView listView;

	private LinearLayout listHeaderView;
	@ViewInject(R.id.productName)
	private TextView productName;
	@ViewInject(R.id.price)
	private TextView price;
	@ViewInject(R.id.buyNumber)
	private EditText buyNumber;
	@ViewInject(R.id.expressPrice)
	private TextView expressPrice;
	@ViewInject(R.id.addressTips)
	private TextView addressTips;
	@ViewInject(R.id.payInfoLayout)
	private LinearLayout payInfoLayout;
	@ViewInject(R.id.payMethodGroup)
	private RadioGroup payMethodGroup;
	@ViewInject(R.id.submitPayBtn)
	private Button submitPayBtn;
	@ViewInject(R.id.cashBalancePay)
	private RadioButton cashBalancePay;

	private static XiaoFeiOrderConfirmObject xiaoFeiOrderConfirmObject;
	private static int requestNo;
	private int selectPayMethod = -1;

	private UserProfile profile;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		homeFragmentInstent = this;
	}

	@Override
	protected View _onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_order_pay_confirm, container, false);
		ViewUtils.inject(this, rootView);
		initView(rootView);
		return rootView;
	}

	private void initView(View rootView) {
		mBaseActivity.setTitle(getResources().getString(R.string.title_pay_confirm));
		mBaseActivity.setTitleLayoutVisibility(true);
		mBaseActivity.setHomeActivity(false);

		payMethodGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup radioGroup, int id) {
				String tag = radioGroup.findViewById(id).getTag().toString();
				selectPayMethod = Integer.valueOf(tag);
				submitPayBtn.setEnabled(true);
			}
		});
		submitPayBtn.setEnabled(false);

		initOrderlView();
		initMyProfileData();
	}

	private void initOrderlView() {
		if (xiaoFeiOrderConfirmObject == null) return;
		//分页
		productName.setText(xiaoFeiOrderConfirmObject.getName());

		payInfoLayout.addView(CommUtil.createSingleLineTextView(mBaseActivity, "购买数量：" + PayConfirmFragment.requestNo));
		payInfoLayout.addView(CommUtil.createSingleLineTextView(mBaseActivity, "购买单价：" + xiaoFeiOrderConfirmObject.getPrice() + "元"));
		payInfoLayout.addView(CommUtil.createSingleLineTextView(mBaseActivity, "物流价格：" + (StringUtils.isNotEmpty(xiaoFeiOrderConfirmObject.getExpressPrice()) ? (xiaoFeiOrderConfirmObject.getExpressPrice() + "元") : "0元")));
		payInfoLayout.addView(CommUtil.createSingleLineTextView(mBaseActivity, "订单编号：" + xiaoFeiOrderConfirmObject.getId()));
		payInfoLayout.addView(CommUtil.createSingleLineTextView(mBaseActivity, "支付编号：" + xiaoFeiOrderConfirmObject.getOrderNo()));
		payInfoLayout.addView(CommUtil.createSingleLineTextView(mBaseActivity, "下单时间：" + xiaoFeiOrderConfirmObject.getCreateTime()));
		payInfoLayout.addView(CommUtil.createSingleLineTextView(mBaseActivity, "支付金额：" + xiaoFeiOrderConfirmObject.getPayMoney() + "元"));
		payInfoLayout.addView(CommUtil.createSingleLineTextView(mBaseActivity, "可获金币：" + (StringUtil.isEmpty(xiaoFeiOrderConfirmObject.getObtainCoin()) ? "0" : xiaoFeiOrderConfirmObject.getObtainCoin()) + "个"));

	}

	@OnClick(R.id.submitPayBtn)
	public void onSubmitPayBtnClick(View view) {
		if (selectPayMethod == -1) {
			ToastUtils.toast(mBaseActivity, "请选择支付方式");
			return;
		} else if (selectPayMethod == 0 && (new BigDecimal(xiaoFeiOrderConfirmObject.getPayMoney()).compareTo(new BigDecimal(profile.getCashBalance())) > 0 || profile.getCashBalance() == 0)) {
			ToastUtils.toast(mBaseActivity, "现金余额不够");
			return;
		}
		switch (selectPayMethod) {
			case 0:
				PayUtil.requestCashBalancePay(mBaseActivity, xiaoFeiOrderConfirmObject.getId(), new PayUtil.OnPayCompleteListener() {
					@Override
					public void onPayComplete(String resultStr) {
						ToastUtils.toast(mBaseActivity, "恭喜，现金余额支付成功！");
						OrderDetailFrament.setXiaoFeiOrderConfirmObject(xiaoFeiOrderConfirmObject);
						CommUtil.openSingleFragmentActivity(mBaseActivity, OrderDetailFrament.class);
						mBaseActivity.finish();
					}
				});
				break;
			case 1:
				PayUtil.requestAlipay(mBaseActivity,
						xiaoFeiOrderConfirmObject.getName(),
						xiaoFeiOrderConfirmObject.getId(),
						xiaoFeiOrderConfirmObject.getOrderNo(),
						xiaoFeiOrderConfirmObject.getPayMoney(),
						new PayUtil.OnPayCompleteListener() {
							@Override
							public void onPayComplete(String resultStr) {
								ToastUtils.toast(mBaseActivity, "恭喜，支付宝支付成功！");
								OrderDetailFrament.setXiaoFeiOrderConfirmObject(xiaoFeiOrderConfirmObject);
								CommUtil.openSingleFragmentActivity(mBaseActivity, OrderDetailFrament.class);
								mBaseActivity.finish();
							}
						});
				break;
			case 2:
				WXPayEntryActivity.setOnPayCompleteListener(new PayUtil.OnPayCompleteListener() {
					@Override
					public void onPayComplete(String resultStr) {
						ToastUtils.toast(mBaseActivity, "恭喜，微信支付成功！");
						OrderDetailFrament.setXiaoFeiOrderConfirmObject(xiaoFeiOrderConfirmObject);
						CommUtil.openSingleFragmentActivity(mBaseActivity, OrderDetailFrament.class);
						mBaseActivity.finish();
					}
				});
				PayUtil.requestWeixinpay(mBaseActivity,
						xiaoFeiOrderConfirmObject.getOrderNo(),
						xiaoFeiOrderConfirmObject.getName(),
						"xiaofei",
						xiaoFeiOrderConfirmObject.getPayMoney(),
						"");
				break;
			default:
				break;
		}
	}

	private void initMyProfileData() {
	HashMap<String, String> paramMap = new HashMap<String, String>();
	paramMap.put("userId", App.sPreferences.getUserId());
	ServiceHelper.send(mBaseActivity, ServiceHelper.GET_MY_PROFILE, paramMap,
			new RequestCallBack<String>() {
				@Override
				public void onStart() {
				}

				@Override
				public void onCancelled() {
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					profile = JsonUtils.parseJsonStrToObject(JsonUtils.getJsonSubStringByKey(responseInfo.result, "body"), UserProfile.class);
					if (profile != null) {
						cashBalancePay.setText("现金余额支付（余额"+profile.getCashBalance()+"元）");
					}
				}

				@Override
				public void onFailure(HttpException error, String msg) {
				}
			});
}


	public static void setXiaoFeiOrderConfirmObject(XiaoFeiOrderConfirmObject xiaoFeiOrderConfirmObject) {
		PayConfirmFragment.xiaoFeiOrderConfirmObject = xiaoFeiOrderConfirmObject;
	}

	public static void setRequestNo(int requestNo) {
		PayConfirmFragment.requestNo = requestNo;
	}

	/**
	 * @return the homeFragmentInstent
	 */
	public static PayConfirmFragment getHomeFragmentInstent() {
		return homeFragmentInstent;
	}

}
